package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	logger "github.com/sirupsen/logrus"
	"net/http"
)

type dingHook struct {
	apiUrl     string //群机器人token
	levels     []logger.Level
	atMobiles  []string    //@谁
	appName    string      //模块前缀
	jsonBodies chan []byte //异步发送内容队列
	closeChan  chan bool   //主进程关闭通道
}

func (dh *dingHook) Levels() []logger.Level {
	return dh.levels
}

func (dh *dingHook) Fire(e *logger.Entry) error {
	msg, _ := e.String()
	dh.DirectSend(msg)
	return nil
}

func (dh *dingHook) DirectSend(msg string) {
	dm := dingMsg{
		MsgType: "text",
	}

	dm.Text.Content = fmt.Sprintf("[alert of hook]\n[app=%s]\n"+
		"[日志详情:%s]", dh.appName, msg)
	dm.At.AtMobiles = dh.atMobiles

	bs, err := json.Marshal(dm)
	if err != nil {
		logger.Errorf("[message marshal failed][error:%v][msg:%v]", err, msg)
		return
	}

	res, err := http.Post(dh.apiUrl, "application/json", bytes.NewBuffer(bs))
	if err != nil {
		logger.Errorf("[send message failed][error:%v][msg:%v]", err, msg)
		return
	}
	if res != nil && res.StatusCode != 200 {
		logger.Errorf("[dingding return error][StatusCode:%v][msg:%v]", res.StatusCode, msg)
		return
	}
}

type dingMsg struct {
	MsgType string `json:"msgtype"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
	At struct {
		AtMobiles []string `json:"atMobiles"`
	} `json:"at"`
}

func main() {
	//glblog.InitLog("debug")
	//glblog.Logger.Info("ingo message")
	//glblog.Logger.Debug("debug message")
	//glblog.Logger.Warning("warning message")
	//glblog.Logger.Error("error message")
	//
	//glblog.Logger.WithFields(logger.Fields{
	//	"animal": "walrus",
	//}).Info("A walrus appears")

	dh := &dingHook{
		apiUrl:     "https://oapi.dingtalk.com/robot/send?access_token=4d2a3d04c7932cee3390e9e033a734c9f2d4a5873d4722eb5b56ac9f0040e57e",
		levels:     []logger.Level{logger.InfoLevel},
		atMobiles:  []string{"13661461543"},
		appName:    "happy time",
		jsonBodies: make(chan []byte),
		closeChan:  make(chan bool),
	}

	//dh.DirectSend("send by direct")
	level := logger.InfoLevel
	logger.SetLevel(level)
	logger.SetReportCaller(true)
	logger.SetFormatter(&logger.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})
	logger.AddHook(dh)
	logger.Info("hook's logrus")
}
